//
//  IMFowardDepartMentController.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/7/30.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMFowardDepartMentController.h"
#import "MicroDef.h"
#import "DepartMemberInfoCell.h"
#import "DepartInfoCell.h"
#import "SettingNormalCell.h"
#import "GroupMemberDetailVC.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CXmppMgr.h"
#import "NSArray+PinYin.h"
#import "GroupMenberCell.h"
#import "CXmppRequestMgr.h"
#import "JKAlertDialog.h"
#import "CFolderMgr.h"
#import "ChildHoodService.h"
#import "CMessageModel.h"
#import "CMessageMgr.h"
#import "CHChatRoomBase.h"
#import "CPresenceModel.h"
#import "CPresenceMgr.h"
#import "WZNavigationController.h"
#import "UIBarButtonItem+category.h"


#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f

@interface IMFowardDepartMentController ()<UITableViewDelegate, UITableViewDataSource>

{
    UITableView *_tableView;
    NSString *_departId;
    NSArray *_departList;
    NSMutableArray *_contactList;
    CContactMgr *_contactMgr;
    CPresenceMgr *_presenceMgr;
    CDepartmentModel *_departMentModel;
    CDepartmentMgr *_departMentMgr;
     NSInteger _contactNum;
}

StrongProperty CContactModel *curContact;
@end

@implementation IMFowardDepartMentController

-(id)initWithDepartId:(NSString *)departId
{
    self = [super init];
    if(self)
    {
        _departId = departId;
    }
    return self;
}

- (void)dealloc
{
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDRECEIVEOFFLINE object:nil];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUsePresence) name:K_XMPPDIDRECEIVEOFFLINE object:nil];
    
    // Do any additional setup after loading the view.
     _contactNum = 0;
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
    
    
    CServerSettingModel *setting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    _departMentMgr = [[CDepartmentMgr alloc] init];
    _departMentModel = [_departMentMgr loadDepartment:_departId];
    _contactMgr = [[CContactMgr alloc] init];
    _presenceMgr = [[CPresenceMgr alloc] init];
    _departList = [_departMentMgr loadDepartments:_departId];
    self.curContact = [_contactMgr loadCurContact];
    
//    [_departList enumerateObjectsUsingBlock:^(CDepartmentModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        _contactNum = 0;
//         obj.UserNum = [self loadDepartMentCountWithDepId:obj.DEPTID];
//    }];
    
    NSArray *array = [NSArray sortArray:[_contactMgr loadContactByDeptID:_departId]];
    _contactList = [NSMutableArray array];
    if (array.count > 0) {
        
        for (CContactModel *contactModel in array) {
            if (![contactModel.UserID isEqualToString:self.curContact.UserID]) {
                [_contactList addObject:contactModel];
            }

        }
}
    
    if (_departMentModel == nil) {
        [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
    } else {
        if (_departMentModel.DepartName.length > 0) {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",_departMentModel.DepartName]];
        } else {
            [self.navigationItem setNewTitleCenter:[NSString stringWithFormat:@"%@",setting.companyName]];
        }
        
    }

     self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.frame;
    _tableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    [_tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, HARDWARE_SCREEN_HEIGHT - 64);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES ];
}
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
        NSInteger rows = 0;
        switch (section) {
            case 0:
                if([_departList count] > 0)
                {
                    rows = [_departList count];
                }
                else
                {
                    rows = [_contactList count];
                }
                break;
            case 1:
                rows = [_contactList count];
                break;
            default:
                rows = 0;
                break;
        }
        return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
        NSInteger section = 0;
        if([_departList count] > 0)
        {
            section ++;
        }
        if([_contactList count] > 0)
        {
            section ++;
        }
        
        return section;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *DepartCellIdentifier = @"DepartInfoCell";
        static NSString *DepartMemberCellIdentifier = @"DepartMemberInfoCell";
//        DLog(@"section:%ld, rows:%ld", (long)indexPath.section, (long)indexPath.row);
        UITableViewCell *cell = nil;
        if(indexPath.section == 0 && [_departList count] > 0)
        {
            DepartInfoCell *departCell = [tableView dequeueReusableCellWithIdentifier:DepartCellIdentifier];
            if (departCell == nil) {
                departCell = [[[NSBundle mainBundle] loadNibNamed:@"DepartInfoCell" owner:self options:nil] objectAtIndex:0];
            }
            
            [departCell.departIcon  setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            departCell.departIcon.layer.cornerRadius = 5.0f/2;
            departCell.departIcon.layer.masksToBounds = YES;
            //            [departCell.departNameLabel setText:[self titleName:indexPath]];
            CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
            [departCell.departNameLabel setText:departModel.DepartName];
            
            
            [departCell.departCountLabel setText:@""];
//            if (departModel.UserNum > 0) {
//                
//                [departCell.departCountLabel setText:[NSString stringWithFormat:@"%zd", departModel.UserNum]];
//                
//            } else {
//            }
            
            if(indexPath.section == 0 && indexPath.row == _departList.count - 1)
            {
                [departCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departCell.seperatorLine setHidden:NO];
            }

            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departCell;
        }
        else
        {
            DepartMemberInfoCell *departMemberCell = [tableView dequeueReusableCellWithIdentifier:DepartMemberCellIdentifier];
            if (departMemberCell == nil) {
                departMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"DepartMemberInfoCell" owner:self options:nil] objectAtIndex:0];
            }
            
            CContactModel *contactModel = [_contactList objectAtIndex:indexPath.row];
            //            [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:[self iconName:indexPath]]];
            CPresenceModel *presence = [_presenceMgr getPresenceWithUserCode:contactModel.UserCode];
            if (presence) {
                if ([presence.IsAvailable isEqualToString:@"在线"] || [presence.pcAvailable isEqualToString:@"在线"]) {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-woman"]];
                    } else {
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-man"]];
                    }
                    
                } else {
                    if ([contactModel.SEX isEqualToString:@"女"]) {
                        
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-womanOffline"]];
                    } else {
                        [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-manOffline"]];
                    }
                    
                    
                }
                
            } else {
                if ([contactModel.SEX isEqualToString:@"女"]) {
                    
                    [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-womanOffline"]];
                } else {
                    [departMemberCell.departMemberIcon setImage:[UIImage imageNamed:@"icon-manOffline"]];
                }
                
            }
            departMemberCell.departMemberIcon.layer.cornerRadius = 5.0f/2;
            departMemberCell.departMemberIcon.layer.masksToBounds = YES;
            
            [departMemberCell.departMemberNameLabel setText:contactModel.UserName];
            [departMemberCell.departMemberJobLabel setText:contactModel.Position];
            if(indexPath.row == _contactList.count - 1)
            {
                [departMemberCell.seperatorLine setHidden:YES];
            }
            else
            {
                [departMemberCell.seperatorLine setHidden:NO];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell = departMemberCell;
        }
        return cell;
}

- (NSInteger)loadDepartMentCountWithDepId:(NSString *)depId
{
    _contactNum = _contactNum + [_contactMgr loadContactCountWithDepartMentId:depId withUserId:self.curContact.UserID];
    NSArray *array = [_departMentMgr loadDepartments:depId];
    for (CDepartmentModel *depModel in array) {
        [self loadDepartMentCountWithDepId:depModel.DEPTID];
    }
    return _contactNum;
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        CGFloat height = 0;
        switch (section) {
            case 0:
                height = KSECTIONHEIGHT;
                break;
            case 1:
                height = KSECTIONHEIGHT;
                break;
            default:
                height = KSECTIONHEIGHT;
                break;
        }
        return height;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0.01;
    //    switch (section) {
    //        case 1:
    //            height = 2;
    //            break;
    //        default:
    //            break;
    //    }
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    //    if(section == 0)
    //    {
    //        return headerView;
    //    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];
        if(section == 0 && [_departList count] > 0)
        {
            [label setText:@"组织"];
        }
        else
        {
            [label setText:@"成员"];
        }
        
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    //    if(section != 1 && [_contactList count] > 0)
    //    {
    //        return headerView;
    //    }
    if(section == 0 && [_departList count] > 0)
    {
        return headerView;
    }
    
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        switch (indexPath.section) {
            case 0:
            {
                if (_departList.count > 0) {
                    CDepartmentModel *departModel = [_departList objectAtIndex:indexPath.row];
                    [self showDepartDetailVC:departModel.DEPTID];
                } else {
                    CContactModel *member = [_contactList objectAtIndex:indexPath.row];
                    CContactModel *model = [_contactMgr loadContactWithUserId:member.UserID];
                    CContactModel *currentUser = [_contactMgr loadContactWithUserId:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId];
                    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"确定发送给:" message:model.UserName];
                    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                        
                        [self fowardWithMember:member withCurUser:currentUser];
                    }];
                    
                    [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                        
                    }];
                    [alert show];
                }
            }
                break;
                
                
            case 1:
            {
                CContactModel *member = [_contactList objectAtIndex:indexPath.row];
                CContactModel *model = [_contactMgr loadContactWithUserId:member.UserID];
                CContactModel *currentUser = [_contactMgr loadContactWithUserId:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId];
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"确定发送给:" message:model.UserName];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                    
                    [self fowardWithMember:member withCurUser:currentUser];
                }];
                
                [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                    
                }];
                [alert show];
            }
                break;
                
            default:
                break;
        }
}



-(void)showDepartDetailVC:(NSString *)currentDepartId
{
    IMFowardDepartMentController *departDetail = [[IMFowardDepartMentController alloc] initWithDepartId:currentDepartId];
    //    CHSNavigationController *departDetailNav = [[CHSNavigationController alloc] initWithRootViewController:departDetail];
    //    [self.leveyTabBarController presentViewController:departDetailNav animated:YES completion:nil];
    [self.navigationController pushViewController:departDetail animated:YES];
    
}


-(void)fowardWithMember:(CContactModel *)member withCurUser:(CContactModel *)currentUser
{
    
    [self dismissViewControllerAnimated:NO completion:^{
       
    }];
   
    CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
    chat.member = member;
    chat.group = nil;
    
    WZNavigationController *rotNav = (WZNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *vc = rotNav.childViewControllers[1];
    [rotNav popToViewController:vc animated:NO];
    
    [rotNav pushViewController:chat animated:YES];
    if ([ChildHoodService defaultService].forwardText !=nil) {
        [[CXmppRequestMgr shareInstance] sendMessageWithMessage:[ChildHoodService defaultService].forwardText messageId:nil curUser:currentUser member:member group:nil];
    }
    if ([ChildHoodService defaultService].fileModel == nil && [ChildHoodService defaultService].imgLocalFilePath.length > 0) {
        UIImage *image = [UIImage imageWithContentsOfFile:[ChildHoodService defaultService].imgLocalFilePath];
        [[CXmppRequestMgr shareInstance] sendImageMessage:image messageId:nil index:0 curUser:currentUser member:member group:nil fileName:nil];
        //            [self cancel];
    } else {
        [[CXmppRequestMgr shareInstance] sendFile:[ChildHoodService defaultService].fileModel messageId:nil curUser:currentUser member:member group:nil];
        //            [self cancel];
    }

}

@end
